<template>
  <div class="news-carousel">
    <div class="carousel-container">
      <el-carousel
        ref="carouselRef"
        :interval="4000"
        type="card"
        height="300px"
        class="carousel"
      >
        <el-carousel-item v-for="(item, index) in announcements" :key="item.id">
          <div
            class="carousel-item"
            :style="{ backgroundImage: `url(${item.img})` }"
          >
            <h3>{{ item.title }}</h3>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <div class="title-section">
      <h3 class="section-title">公告资讯：</h3>
      <div class="title-list">
        <div
          v-for="(item, index) in announcements"
          :key="item.id"
          class="title-item"
          @mouseenter="jumpToSlide(index)"
        >
          {{ item.title }}
          <hr v-if="index < announcements.length - 1" class="divider" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { noticeListService } from '@/api/announcement.js';

const announcements = ref([]);
const carouselRef = ref(null);

const fetchAnnouncements = async () => {
  try {
    const response = await noticeListService();
    announcements.value = response.data.slice(0, 5); // 提取前五个公告
    console.log('公告列表:', announcements.value);
  } catch (error) {
    console.error('获取公告失败:', error);
  }
};

const jumpToSlide = (index) => {
  if (carouselRef.value) {
    carouselRef.value.activeIndex = index; // 切换轮播器到对应的项
  }
};

onMounted(() => {
  fetchAnnouncements();
});
</script>

<style scoped>
.news-carousel {
  display: flex;
  flex-direction: column; /* 垂直排列容器 */
  align-items: center; /* 居中整个容器 */
  margin-top: 40px; /* 添加顶部间距 */
}

.carousel-container {
  width: 70%; /* 设置整体宽度为 70% */
}

.carousel {
  position: relative;
}

.carousel-item {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px; /* 提高轮播项高度 */
  background-color: red; /* 默认背景色 */
  background-size: cover; /* 背景图像覆盖 */
  background-position: center;
  color: white; /* 字体颜色 */
  text-align: center;
}

.title-section {
  width: 70%; /* 设置标题区域宽度与轮播器保持一致 */
  margin-top: 20px; /* 与轮播器的间距 */
}

.section-title {
  font-weight: bold; /* 加粗标题 */
  font-size: 24px; /* 设置标题字体大小 */
  margin-bottom: 10px; /* 标题与内容的间隔 */
}

.title-list {
  display: flex;
  flex-direction: column; /* 垂直排列标题内容 */
}

.title-item {
  padding: 10px 0; /* 内边距，增加可点击区域 */
  color: #333; /* 标题颜色 */
  cursor: pointer; /* 鼠标悬浮手型样式 */
  transition: background-color 0.3s; /* 添加过渡效果 */
  border-bottom: 1px solid #ddd; /* 每个标题的底部边框 */
}

.title-item:hover {
  background-color: #f0f0f0; /* 悬浮时的背景色 */
}

.divider {
  margin: 0; /* 清除分隔线上下边距 */
}
</style>
